part of YFree;

class _YFreeAppPlugin extends _YFreeCommonPlugin {
  @override
  void checkUpdate({
    required int newVersion,
    required String updateContent,
    required String? apkDownloadPath,
    required String? androidAppId,
    required String? iOSAppId,
    bool enableIgnore = false,
    Function()? onNewest,
    BuildContext? context,
  }) {
    PackageInfo.fromPlatform().then((packageInfo) {
      if (newVersion <= int.parse(packageInfo.buildNumber)) {
        onNewest?.call();
        return;
      }
      switch (defaultTargetPlatform) {
        case TargetPlatform.android:
          if (apkDownloadPath == null || apkDownloadPath.isEmpty) {
            UpdateDialog? dialog;
            dialog = UpdateDialog.showUpdate(
              context ?? yPages.last.context,
              width: 250,
              title: "是否升级到最新版本？",
              updateContent: updateContent,
              titleTextSize: 14,
              contentTextSize: 12,
              buttonTextSize: 12,
              // topImage: Image.asset('assets/bg_update_top.png'),
              extraHeight: 5,
              radius: 8,
              themeColor: YConfig.themeColor,
              progressBackgroundColor: YConfig.themeColor.withAlpha(50),
              isForce: true,
              updateButtonText: '立即升级',
              ignoreButtonText: '忽略此版本',
              enableIgnore: enableIgnore,
              onIgnore: () => dialog!.dismiss(),
              onUpdate: () async {
                String savePath = "${(await getExternalStorageDirectory())!.path}/${newVersion}_${DateTime.now().millisecondsSinceEpoch}.apk";
                if (await requestStorage()) {
                  try {
                    Dio().download(
                      apkDownloadPath!,
                      savePath,
                      options: Options(sendTimeout: Duration(microseconds: YConfig.timeOut), receiveTimeout: Duration(microseconds: YConfig.timeOut)),
                      onReceiveProgress: (count, total) {
                        if (count >= total) {
                          dialog!.dismiss();
                          yToast("下载成功");
                          AppInstaller.installApk(savePath);
                          finishApplication();
                          return;
                        }
                        dialog!.update(count / total);
                      },
                    );
                  } catch (e) {
                    dialog!.dismiss();
                    yToast("下载失败，请重试");
                    checkUpdate(newVersion: newVersion, updateContent: updateContent, apkDownloadPath: apkDownloadPath, androidAppId: androidAppId, iOSAppId: iOSAppId, onNewest: onNewest, enableIgnore: enableIgnore);
                  }
                }
              },
            );
          } else {
            if (androidAppId != null) AppInstaller.goStore(androidAppId, "");
          }
          break;
        case TargetPlatform.iOS:
          if (iOSAppId != null) AppInstaller.goStore("", iOSAppId);
          break;
        case TargetPlatform.fuchsia:
          break;
        case TargetPlatform.linux:
          break;
        case TargetPlatform.macOS:
          break;
        case TargetPlatform.windows:
          break;
        case TargetPlatform.ohos:
          break;
      }
    });
  }

  @override
  Future<bool> requestStorage() async {
    return await Permission.storage.request().isGranted;
  }
}
